package com.gmrz.uap.common.db;

import io.shardingjdbc.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingjdbc.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;

import java.util.Collection;

public final class ModuloShardingDatabaseAlgorithm implements PreciseShardingAlgorithm<String> {

    @Override
    public String doSharding(final Collection<String> dbNames, final PreciseShardingValue<String> shardingValue) {
        Integer databaseShardingCount = DataSourceShardingConst.getConfigInfoInt(DataSourceShardingConst.DATASOURCE_DATABASE_VISUAL_NODE_COUNT);
        Integer value = shardingValue.getValue().substring(0, 4).hashCode();

        if (!DataSourceShardingConst.SHARDING_TABLE_LIST.contains(shardingValue.getLogicTableName())) {
            return dbNames.iterator().next();
        }

        String rangeList = DataSourceShardingConst.getConfigInfo(DataSourceShardingConst.DATASOURCE_DATABASE_VISUAL_NODE_RANGE);
        Integer physicCount = DataSourceShardingConst.getPhysicNodeByVisualNode(value % databaseShardingCount,rangeList);

        for (String each : dbNames) {
            if (each.endsWith(physicCount + "")) {
                return each;
            }
        }
        throw new UnsupportedOperationException();
    }
}
